// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log("input params: ", event)
  // 判断条件
  if (event.returnCode == 'SUCCESS' && event.resultCode == 'SUCCESS') {
    const _ = db.command
    try {
      // 更新订单
      await updateOrder({
        // appid: event.subAppid, // 小程序的APPID
        _openid: event.subOpenid, // 小程序用户的openid
        outTradeNo: event.outTradeNo, // 商户号的订单号
        payStatus: _.neq('success')
      }, {
        transactionId: event.transactionId, // 微信方的订单号
        totalFee: event.totalFee * 0.01, // 微信方收到的金额
        timeEnd: event.timeEnd, // 支付结束时间
        payStatus: 'success',
        status: '待配送',
        updateTime: new Date().getTime(),
        payOffline: false,
      })

      await vipUpgrade({
        _openid: event.subOpenid
      })

      await notifyDeliveryMen(event.subOpenid, event.outTradeNo)

      return {
        errcode: 0,
        errmsg: 'SUCCESS'
      }
    } catch (err) {
      console.log(err)
    }
  }
  // 支付回调的返回协议和入参协议（必须返回此结构体，详见文档）
  return {
    errcode: -1,
    errmsg: 'FAIL'
  }
}

const updateOrder = async (whereObj, updateData) => {
  return await db.collection('orders')
    .where(whereObj)
    .update({
      data: updateData
    })
}

const vipUpgrade = async (data) => {
  const {
    _openid
  } = data
  const vipMinFee = 300

  let totalFee = 0
  const _ = db.command
  const resOrders = await db.collection('orders')
    .where({
      _openid,
      ticketOrderId: _.exists(false)
    })
    .get()

  const ordersData = resOrders.data || []
  ordersData.forEach(ele => {
    totalFee += (ele.totalFee * 1)
  })

  if (totalFee >= vipMinFee) {
    await db.collection('users')
      .where({
        _openid
      })
      .update({
        data: {
          vip: '1'
        }
      })
  }
}

const notifyDeliveryMen = async (openid, outTradeNo) => {
  const resOrder = await db.collection('orders')
    .where({
      _openid: openid,
      outTradeNo,
      ticketInfo: db.command.exists(false)
    })
    .get()
  const order = resOrder.data[0]
  if (!order) return false

  return await cloud.callFunction({
    name: 'notifyDelivery',
    data: {
      orderId: order._id
    }
  })
}